package com.wangcp.springboottenant.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.Parenthesis;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;

public class MyTenantLineInnerInterceptor extends TenantLineInnerInterceptor {

    public MyTenantLineInnerInterceptor(TenantLineHandler tenantLineHandler) {
        super(tenantLineHandler);
    }

    @Override
    protected Expression builderExpression(Expression currentExpression, Table table) {
        Column aliasColumn = this.getAliasColumn(table);
        if(table.getName().equals("users")){
            InExpression inExpression = new InExpression();
            inExpression.setLeftExpression(aliasColumn);
            inExpression.setRightExpression(getTenantLineHandler().getTenantId());
            if(currentExpression == null){
                return inExpression;
            }else{
                return currentExpression instanceof OrExpression ? new AndExpression(new Parenthesis(currentExpression),inExpression):new AndExpression(currentExpression,inExpression);
            }
        }else{
            // 调用父级
            return super.builderExpression(currentExpression, table);
        }
    }
}
